<template>
  <div class="container">
    <div class="header">
      <el-date-picker
        value-format="yyyy-MM-dd"
        style="margin-right: 10px"
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>

      <el-button type="primary" icon="el-icon-search" @click="handleSearch()"
        >查询</el-button
      >
      <el-button type="danger" icon="el-icon-delete" @click="empty()"
        >清空</el-button
      >
      <el-button type="success" icon="el-icon-tickets" @click="generateBtn()"
        >生成要票单</el-button
      >
      <el-button type="success" icon="el-icon-tickets" @click="generatesBtn()"
        >生成全部要票单</el-button
      >
    </div>
    <div class="header">
      <el-select
        v-model="supplier_code"
        clearable
        filterable
        placeholder="请选择供应商"
      >
        <el-option
          v-for="item in supplierList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        >
        </el-option>
      </el-select>
      <!-- <el-select
        clearable
        v-model="inside.value"
        :multiple="false"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请选择供应商"
        :remote-method="insideRemoteMethod"
        :loading="inside.loading"
      >
        <el-option
          v-for="item in inside.list"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select> -->
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addSupplier()"
        >添加</el-button
      >
    </div>
    <el-tag
      class="tagCenter"
      v-for="tag in supplierTag"
      :type="tag.type"
      :key="tag.name"
      @click="tagClick(tag)"
      @close="handleClose(tag)"
      closable
    >
      {{ tag.name }}
    </el-tag>
    <el-table
      max-height="600"
      :data="tableData"
      border
      tooltip-effect="dark"
      ref="multipleTables"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      empty-text="暂无数据"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="goods_name"
        label="名称"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="goods_code"
        label="Code"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="goods_num"
        label="数量"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="goods_price"
        label="价格"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="unit"
        label="单位"
        align="center"
      ></el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <pagination
      @page="handleSizeChange"
      @pagesize="handleCurrentChange"
      :pageData="pageData"
    ></pagination> -->
  </div>
</template>
<script>
import Pagination from "@/components/pagination";
import {
  getSmkPurchaseMerge,
  generateSmk,
  getSupplierOptions
} from "@/api/bill";
import { getnowDate } from "@/utils/index";
import { supplierList } from "@/api/supplier/supplierList";
export default {
  components: {
    pagination: Pagination
  },
  data() {
    return {
      //页面数据
      tableData: [],
      search: {
        start_time: "",
        end_time: ""
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      },
      supplier_code: "",
      normal_startime: getnowDate().settlementStarTimers,
      normal_endtime: getnowDate().endtimers,
      date: [],
      supplierTag: [],
      supplierList: [],
      tabCenter: [],
      tabMain: {},
      //分页
      pageData: {
        pageSizes: [10, 20],
        pageSize: 10,
        page: 1,
        total: null,
        layout: "total, sizes, prev, pager, next, jumper"
      }
    };
  },
  created() {
    this.search.start_time = this.normal_startime;
    this.search.end_time = this.normal_endtime;
    // this.search.start_time = "2024-09-01";
    // this.search.end_time = "2024-09-02";
    if (this.normal_startime) {
      this.date.push(this.search.start_time);
    }
    if (this.normal_endtime) {
      this.date.push(this.search.end_time);
    }
    //页面数据
    this.getData();
    // this.getSupplierList();
  },
  methods: {
    //页面数据
    getData() {
      let data = {
        limit: this.pageData.pageSize,
        page: this.pageData.page,
        start_date: this.search.start_time,
        end_date: this.search.end_time,
        warehouse_code: "",
        buyer_code: "",
        // supplier_code: "01000016",
        // supplier_code: this.inside.value
        supplier_code: ""
      };
      getSmkPurchaseMerge(data)
        .then(res => {
          this.tabCenter = res.data.list;

          res.data.list.forEach(item => {
            this.supplierList.push({
              name: `${item.supplier_name}(${item.supplier_code})`,
              code: item.supplier_code
            });
          });
          this.tableData = res.data.list[0].goods;
          this.supplierTag.push({
            name: res.data.list[0].supplier_name,
            code: res.data.list[0].supplier_code,
            type: ""
          });
          this.supplier_code = res.data.list[0].supplier_code;
          this.tabMain[res.data.list[0].supplier_code] = [];
        })
        .catch(err => {});
    },
    //添加计供应商
    addSupplier() {
      if (this.supplier_code) {
        let bool = this.supplierTag.filter(item => {
          return item.code == this.supplier_code;
        });
        if (bool.length > 0) {
          this.$message({
            type: "info",
            message: "该供应商已添加"
          });
        } else {
          this.supplierTag.forEach(item => {
            item.type = "info";
          });
          this.tabCenter.forEach(item => {
            if (item.supplier_code == this.supplier_code) {
              this.supplierTag.push({
                name: item.supplier_name,
                code: item.supplier_code,
                type: ""
              });
              this.tableData = item.goods;
              this.tabMain[item.supplier_code] = [];
            }
          });
          console.log(this.tabMain, 22222);
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择供应商"
        });
      }
    },
    handleClose(tag) {
      this.supplierTag.splice(this.supplierTag.indexOf(tag), 1);
      Reflect.deleteProperty(this.tabMain, tag.code);
      if (tag.type == "") {
        this.tableData = [];
      }
      console.log(this.tabMain, 11111);
    },
    tagClick(tag) {
      this.supplierTag.forEach(item => {
        item.type = "info";
      });
      this.supplierTag[this.supplierTag.indexOf(tag)].type = "";
      this.supplier_code = tag.code;
      this.tabCenter.forEach(item => {
        if (item.supplier_code == tag.code) {
          this.tableData = item.goods;
        }
      });
      if (this.tabMain[this.supplier_code].length > 0) {
        this.tableData.forEach((res, index) => {
          this.tabMain[this.supplier_code].forEach(row => {
            if (res.key == row) {
              this.$nextTick(() => {
                this.$refs.multipleTables.toggleRowSelection(
                  this.tableData[index],
                  true
                );
              });
            }
          });
        });
      }
    },
    // // 嵌套搜索供应商数据
    // insideRemoteMethod(query) {
    //   if (query !== "") {
    //     this.getSupplierList(query);
    //   } else {
    //     this.inside.options = [];
    //   }
    // },
    // //获取供应商数据
    // getSupplierList(query = "") {
    //   this.inside.loading = true;
    //   console.log(query, 89898989);
    //   this.inside.list = this.tabCenter.map(item => {
    //     console.log(item.supplier_name, 88888);
    //     if (item.supplier_name == query) {
    //       return {
    //         value: `${item.supplier_code}`,
    //         label: `${item.supplier_name}`
    //       };
    //     }
    //   });
    //   this.inside.loading = false;
    // },
    //生成要票单
    generateBtn() {
      if (Object.keys(this.tabMain).length != 0) {
        this.$confirm("是否生成要票单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let supplierList = Object.keys(this.tabMain);
            let data = {
              start_date: this.search.start_time,
              end_date: this.search.end_time,
              warehouse_code: "",
              buyer_code: "",
              supplier_code: supplierList.join(","),
              choose: JSON.stringify(this.tabMain)
            };
            generateSmk(data).then(res => {
              if (res.code == 0) {
                this.supplier_code = "";
                this.tableData = [];
                this.supplierTag = [];
                this.supplierList = [];
                this.tabCenter = [];
                this.tabMain = {};
                this.getData();
                this.$message({
                  type: "success",
                  message: res.msg
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else {
        this.$message({
          type: "info",
          message: "请勾选数据"
        });
      }
    },
    //生成全部要票单
    generatesBtn() {
      this.$confirm("是否生成全部要票单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let supplierList = Object.keys(this.tabMain);
          let data = {
            is_all: 1,
            start_date: this.search.start_time,
            end_date: this.search.end_time,
            warehouse_code: "",
            buyer_code: "",
            supplier_code: supplierList.join(","),
            choose: JSON.stringify(this.tabMain)
          };
          generateSmk(data).then(res => {
            if (res.code == 0) {
              this.supplier_code = "";
              this.tableData = [];
              this.supplierTag = [];
              this.supplierList = [];
              this.tabCenter = [];
              this.tabMain = {};
              this.getData();
              this.$message({
                type: "success",
                message: res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 搜索
    handleSearch() {
      if (this.date.length > 0) {
        this.search.start_time = this.date[0];
        this.search.end_time = this.date[1];
      }
      this.supplier_code = "";
      this.tableData = [];
      this.supplierTag = [];
      this.supplierList = [];
      this.tabCenter = [];
      this.tabMain = {};
      this.pageData.total = null;
      this.pageData.page = 1;
      this.getData();
    },
    //清空
    empty() {
      this.date = [];
      this.date.push(this.normal_startime);
      this.date.push(this.normal_endtime);
      this.search = {
        start_time: "",
        end_time: ""
      };
      this.supplier_code = "";
      this.tableData = [];
      this.supplierTag = [];
      this.supplierList = [];
      this.tabCenter = [];
      this.tabMain = {};
    },

    //每页多少条
    handleCurrentChange(val) {
      this.pageData.page = 1;
      this.pageData.pageSize = val;
      this.getData();
    },
    //选取页数
    handleSizeChange(page) {
      this.pageData.page = page;
      this.getData();
    },
    //勾选
    handleSelectionChange(val) {
      console.log(val, 67676767);
      let arrId = [];
      val.forEach(res => {
        arrId.push(res.key);
      });
      if (this.supplier_code) {
        if (this.tabMain[this.supplier_code].length == 0) {
          this.tabMain[this.supplier_code] = arrId;
        } else {
          this.tableData.forEach(res => {
            this.tabMain[this.supplier_code].forEach((row, index) => {
              if (res.key == row) {
                this.tabMain[this.supplier_code].splice(index, 1);
              }
            });
          });
          this.tabMain[this.supplier_code] = [
            ...this.tabMain[this.supplier_code],
            ...arrId
          ];
          console.log(this.tabMain, 333);
        }
      }
    }
  }
};
</script>
<style scoped>
.header {
  margin-bottom: 10px;
}
.search {
  width: 200px;
  margin-right: 10px;
}
</style>
